<template>
  <div class="staff-management">
    <a-row type="flex" justify="center" align="top">
      <a-col :span="4">
        <a-tree style="width:228px;min-height: 423px;max-height: 600px; overflow-y: auto" :tree-data="departmentData" :expandedKeys="expandedKeys" :selectedKeys="selectedKeys" :replaceFields="{ title: 'name', key: 'id' }" @select="getJd" @expand="onExpand"></a-tree>
        <div class="line"></div>
      </a-col>
      <a-col :span="18">
        <a-row type="flex" justify="space-between" align="middle" style="margin-bottom: 20px">
          <a-form layout="inline">
            <a-form-item label="关键字">
              <a-input v-model="searchField" placeholder="请输入姓名/手机号" allow-clear style="width: 220px" @change="onChangeSearch">
                <a-icon slot="prefix" type="user" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" icon="search" @click="onSearch">查询</a-button>
            </a-form-item>
          </a-form>
          <a-button @click="addRole" icon="plus" :disabled="selectedRowKeys.length <= 0">批量添加角色</a-button>
        </a-row>
        <ownTable :columns="columns" :dataSource="dataSource" :selectedRowKeys="selectedRowKeys" @selectedKeys="getSelectedRow" :page="memberState.pageNum" :pageSize="memberState.pageSize" :total="total" @pageChange="onPageChange" @sizeChange="onSizeChange">
          <template slot="operation" slot-scope="record">
            <a class="ant-dropdown-link" @click="onDetail(record)">详情</a>
          </template>
        </ownTable>
      </a-col>
    </a-row>
    <!-- 添加角色弹窗 -->
    <a-modal title="添加角色" v-model="isChangePosition" @ok="handleOk" @cancel="handleCancel" :afterClose="onCloseModal">
      <a-form-model ref="changePosition" :model="changePositionForm" :rules="changePositionRules" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
        <a-form-model-item label="已选员工" prop="employees">
          <a-tag v-for="item in changePositionForm.employees" :key="item.id" closable @close="onDelete(item.id)">{{ item.realName }}</a-tag>
        </a-form-model-item>
        <a-form-model-item label="选择角色" prop="position">
          <a-select v-model="changePositionForm.position" placeholder="请选择角色" allow-clear>
            <a-select-option v-for="item in roleList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="备注内容" prop="note">
          <a-textarea v-model="changePositionForm.note" :max-length="300" :auto-size="{ minRows: 5 }" placeholder="输入内容" allow-clear />
          <span style="position: absolute;right: 10px;bottom: -5px;color: #ccc;">{{ changePositionForm.note.length }}/300</span>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <drawer title="员工详情" ref="drawer" :visible.sync="detailDrawer">
      <staffDetail slot="content" :staff="nowStaff"></staffDetail>
    </drawer>
  </div>
</template>

<script>
import { isNumber, regTest } from '@/utils/util';
import ownTable from '../modal/Table.vue';
import Drawer from '@/pages/components/drawer';
import staffDetail from './personalDetails.vue';
import { queryEmplyee, topDepartment, subDepartment } from '@/services/staff';
import { addMemeber, roleNameList } from '@/services/role';
export default {
  name: 'staffManagement',
  components: { ownTable, Drawer, staffDetail },
  props: ['apply'],
  watch: {
    apply: {
      handler (val) {
        if (val) {
          // 获取组织架构一级部门
          this.getTopDepartment();
          // 获取默认员工列表
          this.getMemberList(this.memberState);
        }
      }
    }
  },
  data () {
    return {
      departmentData: [
        {
          name: '组织架构',
          id: '0-0',
          children: [],
        },
      ],
      searchField: '',
      detailDrawer: false,
      selectedRowKeys: [],
      changePositionForm: {
        employees: [],
        position: undefined,
        note: '',
      },
      nowStaff: {},
      changePositionRules: {
        employees: [
          {
            required: true,
            message: '必须选择员工！',
            trigger: ['change', 'blur'],
          },
        ],
        position: [
          {
            required: true,
            message: '必须选择职务！',
            trigger: 'change',
          },
        ],
        note: [
          {
            required: true,
            message: '内容不允许为空！',
            trigger: 'blur',
          },
        ],
      },
      columns: [
        {
          title: '姓名',
          dataIndex: 'realName',
        },
        {
          title: '部门',
          dataIndex: 'deptNames',
        },
        {
          title: '角色',
          dataIndex: 'roleNames',
        },
        {
          title: '手机',
          dataIndex: 'mobile',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      dataSource: [],
      isChangePosition: false,
      memberState: {
        realName: '',
        mobile: '',
        deptId: '',
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      selectedKeys: [],
      roleList: [],
      expandedKeys: ['0-0'],
    };
  },
  methods: {
    onChangeSearch (e) {
      this.searchField = e.target.value;
      this.memberState.realName = e.target.value;
    },
    /**
     * @description: 选中组织架构一级部门时获取下级部门
     * @param {*} selectedKeys
     * @return {*}
     */
    getJd (selectedKeys, e) {
      const id = selectedKeys[0];
      var bool = this.expandedKeys.includes(id);
      let item = e.selectedNodes[0].data.props.dataRef;
      if (!bool && item?.isExistChild) {
        // 获取下级部门
        subDepartment({ id }).then(res => {
          let { code, data, msg } = res.data;
          if (code == 200) {
            if (data?.childrenList) {
              item.children = data.childrenList;
              this.expandedKeys.push(id);
            } else {
              this.$message.error(msg);
            }
          }
        });
      }
      this.memberState.realName = '';
      this.memberState.mobile = '';
      this.memberState.deptId = selectedKeys[0];
      this.getMemberList(this.memberState);
    },
    onExpand (val) {
      this.expandedKeys = val;
    },
    onSearch () {
      this.memberState.deptId = '';
      this.selectedKeys = [];
      if (isNumber(this.searchField)) {
        if (regTest.mobileReg(this.searchField)) {
          this.memberState.mobile = this.searchField;
          this.memberState.realName = '';
        }
      } else {
        this.memberState.realName = this.searchField;
        this.memberState.mobile = '';
      }
      this.getMemberList(this.memberState);
    },
    onDetail (item) {
      this.detailDrawer = true;
      this.nowStaff = item;
    },
    addRole () {
      this.isChangePosition = true;
      this.getRoleNameList();
    },
    onDelete (id) {
      this.selectedRowKeys = this.selectedRowKeys.filter(val => val != id);
    },
    handleOk () {
      this.$refs.changePosition.validate(valid => {
        if (valid) {
          this.getAdd();
          this.selectedRowKeys = [];
        } else {
          return false;
        }
      });
      this.isChangePosition = false;
    },
    handleCancel () {
      this.selectedRowKeys = [];
      this.changePositionForm.employees = [];
      this.$refs.changePosition.resetFields();
    },
    getSelectedRow (data) {
      this.selectedRowKeys = data.selectedRowKeys;
      this.changePositionForm.employees = data.selectedRows;
    },
    onCloseModal () {
      this.handleCancel();
    },
    /**
     * @description: 分页
     * @param {*} page
     * @param {*} pageSize
     * @return {*}
     */
    onPageChange (data) {
      this.memberState.pageNum = data.page;
      this.memberState.pageSize = data.pageSize;
      this.getMemberList(this.memberState);
    },
    onSizeChange (data) {
      this.memberState.pageNum = 1;
      this.memberState.pageSize = data.size;
      this.getMemberList(this.memberState);
    },
    /**
     * @description: 获取组织架构一级部门
     * @param {*}
     * @return {*}
     */
    getTopDepartment () {
      topDepartment().then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          data.map(val => (val.isExistChild = true));
          this.departmentData[0].children = data;
        } else {
          this.$message.error(msg);
        }
      });
    },
    /**
     * @description: 获取员工分页列表
     * @param {*}
     * @return {*}
     */
    getMemberList (params) {
      queryEmplyee(params).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.dataSource = data.content;
          this.total = data.totalElements;
        } else {
          this.$message.error(msg);
        }
      });
    },
    /**
     * @description: 获取角色下拉列表
     * @param {*}
     * @return {*}
     */
    getRoleNameList () {
      roleNameList().then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.roleList = data;
        } else {
          this.$message.error(msg);
        }
      });
    },
    /**
     * @description: 添加人员接口
     * @param {*}
     * @return {*}
     */
    getAdd () {
      let params = {
        roleId: this.changePositionForm.position,
        userIds: this.selectedRowKeys.toString(),
        status: 0,
      };
      addMemeber(params).then(res => {
        let { code, data, msg } = res.data;
        if (code == 200) {
          this.$message.success(msg);
        } else {
          this.$message.error(msg);
        }
      });
    },
  },
  created () {
    // 获取组织架构一级部门
    this.getTopDepartment();
    // 获取默认员工列表
    this.getMemberList(this.memberState);
  },
};
</script>

<style scoped lang="less">
.ant-list-item-meta-content {
  display: flex;
}
.ant-list-item-meta-title {
  margin-right: 10px;
}
.staff-management {
  background: #fff;
  padding: 24px;
}
.ant-list-item-meta-description {
  font-size: 12px !important;
}
.ant-list-item-action {
  margin: none !important;
}
.ant-col.ant-col-4 {
  width: 228px;
  display: flex;
}
.ant-col.ant-col-18 {
  flex: 1;
  padding-left: 24px;
}
.line {
  width: 1px;
  height: 780px;
  background: #f0f0f0;
  position: absolute;
  left: 227px;
  top: -25px;
}
.staff-mandetail {
  /deep/ .ant-drawer-body {
    padding: 0 24px;
  }
}
</style>
